import api from '../../api/api'
import {category, goodstocart, goodstocheckout, productId, search} from "../../api/conf";
import Toast from 'tdesign-miniprogram/toast/index';

Page({
  data: {
    searchValue: '',
    cateId: 0,
    minPrice: '',
    maxPrice: '',
    orderBy: 0, // 默认:综合 0|名称升序:5|名称降序:6|销量升序:20|销量降序:21
    page: 1,
    size: 6,
    categoryList: {
      id: 0,
      label: '分类',
      defaultLabel: '分类',
      value: null,
      options: [],
    },
    complex: {
      id: 0,
      label: '综合',
      defaultLabel: '综合',
      value: null,
      options: [
        {
          label: "销量升序", 
          value: 0, 
          checked: false, 
          id: 20,
        }, 
        {
          label: "价格升序",
          value: 1,
          checked: false,
          id: 10,
        }, 
        {
          label: "价格降序",
          value: 2,
          checked: false,
          id: 11,
        }
      ]
    },
    priceRange: {
      label: '价格区间',
      defaultLabel: '价格区间',
      value: null,
      options: [
        {
          label: "0-200",
          value: 0,
          checked: false,
          id: [0, 200],
        },
        {
          label: "200-500",
          value: 1,
          checked: false,
          id: [200, 500],
        },
        {
          label: "500-1000",
          value: 2,
          checked: false,
          id: [500, 1000],
        },
        {
          label: "1000以上",
          value: 3,
          checked: false,
          id: [1000, ''],
        },
      ]
    },
    goodsListLoadStatus: 0,
    goodsList: [],
    addCartGoodInfo: null,
    isSpuSelectPopupShow: false,
    checkSkuIdArr: [],
    goodsId: 0,
    buyNum: 1,
  },

  onLoad: function () {
  },
  onShow: function (){
    this.getTabBar().init();
    // 页面渲染完成
    this.onLoadGoodsList()
    this.getCategoryList()
  },
  onLoadGoodsList: function () {
    this.setData({
      goodsList: [],
      page: 1,
      goodsListLoadStatus: 0
    })
    this.getGoodsList()
  },
  getCategoryList: function () {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wx.showNavigationBarLoading()
    api.get(category, {}).then(res => {
      let categoryList = []
      res.Data.forEach((item, index) => {
        let category = {
          label: item.Name,
          value: index,
          checked: false,
          id: item.Id,
        }
        categoryList.push(category)
      })
      this.setData({
        'categoryList.options': categoryList
      })
      wx.hideLoading()
      wx.hideNavigationBarLoading()
    })
  },
  clearHandle: function () {
    this.setData({
      searchValue: ''
    })
  },
  submitHandle: function ({detail}) {
    this.setData({
      searchValue: detail.value,
    })
    this.onLoadGoodsList();
  },
  onReachBottom() {
    if (this.data.goodsListLoadStatus !== 0 || this.data.goodsList.length <= 0) {
      return;
    }
    this.setData({
      page: this.data.page + 1
    })
    this.getGoodsList()
  },
  async getGoodsList() {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wx.showNavigationBarLoading()
    this.setData({ goodsListLoadStatus: 1 });
    await api.get(search, {
      q: this.data.searchValue,
      cid: this.data.cateId,
      minPrice: this.data.minPrice,
      maxPrice: this.data.maxPrice,
      orderBy: this.data.orderBy,
      page: this.data.page,
      size: this.data.size
    }).then( res => {
      this.setData({
        goodsList: this.data.goodsList.concat(res.Data.Items),
        goodsListLoadStatus: 0,
      })
      if (res.Data.Paging.TotalPage === this.data.page) {
        this.setData({
          goodsListLoadStatus: 2
        })
      }
      wx.hideLoading()
      wx.hideNavigationBarLoading()
    })
  },
  onSelectChange: function (e) {
    const { type } = e.currentTarget.dataset
    const { value } = e.detail
    let listData = this.data[type]
    let id = null;
    if(listData.options[value].checked){
      listData.options[value].checked = false
      listData.label = listData.defaultLabel
      listData.value = null
    }else{
      if(listData.value !== null && listData.value !== value){
        listData.options[listData.value].checked = false
      }
      listData.options[value].checked = true
      listData.label = listData.options[value].label
      listData.value = value
      id = listData.options[value].id
    }
    switch (type) {
      case 'categoryList':
        this.setData({categoryList: listData, cateId: id});
        break
      case 'complex':
        this.setData({complex: listData, orderBy: id});
        break
      case 'priceRange':
        this.setData({priceRange: listData, minPrice: id[0], maxPrice: id[1]});
        break
    }
    this.onLoadGoodsList()
  },
  goodListClickHandle: function (e) {
    let detailId = e.detail.goods.Id
    wx.navigateTo({
      url: '/pages/detail/detail?id=' + detailId
    })
  },
  goodListAddCartHandle: function (e) {
    let goodsId = e.detail.goods.Id
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wx.showNavigationBarLoading()
    api.get(productId, {
      id: goodsId
    }).then( res => {
      const addCartGoodInfo = res.Data
      this.setData({
        goodsId,
        addCartGoodInfo,
        isSpuSelectPopupShow: true,
        buyNum: 1
      })
      wx.hideLoading()
      wx.hideNavigationBarLoading()
    })
  },

  handlePopupHide: function() {
    this.setData({
      isSpuSelectPopupShow: false,
    });
  },

  handleChooseItem: function ({ detail }) {
    this.setData({
      checkSkuIdArr: detail.checkSkuIdArr,
    })
  },

  handleAddCart: function (e) {
    const eventStatus = this.checkOutEvent()
    if(!eventStatus ){return}
    let buyNum = this.data.buyNum
    api.post(goodstocart, {
      PId: this.data.goodsId,
      Qty: buyNum,
      AttrValue: JSON.stringify(this.data.checkSkuIdArr)
    }).then( res => {
      this.setData({isSpuSelectPopupShow: false})
      Toast({
        context: this,
        selector: '#t-toast',
        message: '成功加入购物车',
      });
    })
  },
  handleBuyNumChange: function (e) {
    const {value} = e.detail
    this.setData({
      buyNum: value
    })
  },
  gotoBuy: function () {
    const eventStatus = this.checkOutEvent()
    if(!eventStatus){
      return
    }
    api.post(goodstocheckout, {
      PId: this.data.goodsId,
      Qty: this.data.buyNum,
      AttrValue: JSON.stringify(this.data.checkSkuIdArr)
    }).then(res => {
      wx.navigateTo({
        url: '/pages/checkout/checkout',
      })
    })
  },

  checkOutEvent: function () {
    const checkSkuIdArr = this.data.checkSkuIdArr
    const {isSpuSelectPopupShow} = this.data

    if(!isSpuSelectPopupShow){
      this.setData({isSpuSelectPopupShow: true })
      return false
    }

    if(checkSkuIdArr.length === 0 || checkSkuIdArr.includes(0)){
      Toast({
        context: this,
        selector: '#t-toast',
        message: '请选择规格',
      });
      return false
    }
    return true
  },
})